//
//  YZAutoCache.m
//  VET
//
//  Created by Lam BG on 2018/7/17.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAutoCache.h"

#import "YZAutoItemModel.h"

#import "YZBaseAPI.h"

#import "MJExtension.h"

@interface YZAutoCache ()

@property (nonatomic, strong) NSMutableDictionary *cache;

@property (nonatomic, strong) YZBaseAPI *itemsAPI;

@end

@implementation YZAutoCache

SingletonM

#define kDictKey @"dictKey"

/* 根据 key 获取当前 cell 的选择值 */
- (RACSignal*)getAutoCellItems:(NSString*)key {
    
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
       
        NSDictionary *itemDict = self.cache[key];
        if (itemDict.count == 0) {
            
            // 网络获取
            [[self.itemsAPI getRequest] subscribeNext:^(id data) {
                
                // 避免服务器返回 null
                if (kNullable(data) != nil) {
                    
                    // 缓存
                    [self.cache removeAllObjects];
                    [self.cache setDictionary:data];
//                    UserDefaultsAsyncSavaObjToLocal(kDictKey, self.cache);
                    
                    // 返回
                    NSArray *items = [YZAutoItemModel mj_objectArrayWithKeyValuesArray:data[key]];
                    [subscriber sendNext:items];
                    [subscriber sendCompleted];
                } else {
    
                    YZAutoItemModel *item = [[YZAutoItemModel alloc] init];
                    item.itemKey = 1;
                    item.itemValue = @"服务器获取数据错误";
                    [subscriber sendNext:@[item]];
                    [subscriber sendCompleted];
                }
                
            } error:^(NSError * _Nullable error) {
                
                [subscriber sendError:error];
                [subscriber sendCompleted];
            }];
        } else {
            
            // 有缓存直接返回
            NSArray *items = [YZAutoItemModel mj_objectArrayWithKeyValuesArray:itemDict];
            [subscriber sendNext:items];
            [subscriber sendCompleted];
        }
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

#pragma mark - getter

- (NSMutableDictionary *)cache {
    
    if (_cache == nil) {
        
        // 从本地获取
//        _cache = UserDefaultsGetObjFromLocal(kDictKey);
        if (_cache == nil) {
            
            _cache = [NSMutableDictionary dictionary];
        }
    }
    
    return  _cache;
}

- (YZBaseAPI *)itemsAPI {
    
    if (_itemsAPI == nil) {
        
        _itemsAPI = [YZBaseAPI api];
        _itemsAPI.action = @"/api/dictionary/values";
        _itemsAPI.showLoadingStatus = YES;
    }
    
    return _itemsAPI;
}

@end













